package com.glc.hms.system.controller.web;


import com.glc.hms.common.controller.BaseController;
import com.glc.hms.common.data.ResponseData;
import com.glc.hms.common.data.SuccessResponseData;
import com.glc.hms.core.annotation.SysLogAnno;
import com.glc.hms.core.shiro.ShiroUser;
import com.glc.hms.core.shiro.ShiroUtil;
import com.glc.hms.system.model.param.UserLoginParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;


/**
 * 登录控制器
 */
@Slf4j
@Api(value = "登录", description = "登录接口", basePath = "/webApi/index")
@RestController
@RequestMapping("/webApi/index")
public class LoginContrller extends BaseController {

    /**
     * 登录验证
     */
    @ApiOperation(value = "登录验证", response = ResponseData.class)
    @SysLogAnno(value = "登录验证",type = 1)
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(@RequestBody UserLoginParam userLoginParam
                        , HttpServletRequest request) {


        //先查询账号状态
        String password = userLoginParam.getPassword();
        String username = userLoginParam.getUsername();
        String remember = userLoginParam.getRemember();

        Subject currentUser = ShiroUtil.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());

        //如果开启了记住我功能
        if ("on".equals(remember)) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }
        currentUser.login(token);
        //记录登陆者的ip和登陆时间

        //登录成功，记录登录日志
        ShiroUser shiroUser = ShiroUtil.getUserNotNull();
        ShiroUtil.getSession().setAttribute("sessionFlag", true);
        HashMap<String, Object> result = new HashMap<>();
        result.put("userId", shiroUser.getUserId());
        result.put("username", shiroUser.getUsername());
        return new SuccessResponseData(result);
    }


    /**
     * 退出登录
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ResponseData  logOut() {
        ShiroUtil.getSubject().logout();
        deleteAllCookie();
        return SUCCESS_TIP;
    }

}
